<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="订单编号" prop="cardOrderNumber">
              <el-input v-model="queryParams.cardOrderNumber" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户玩家号" prop="userInviteCode">
              <el-input v-model="queryParams.userInviteCode" placeholder="请输入用户玩家号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-tabs type="card" v-model="queryParams.logisticsStatus" @tab-change="handleQuery">
        <el-tab-pane label="全部" name="-1"/>
        <el-tab-pane label="待发货" name="2"/>
        <el-tab-pane label="待收货" name="3"/>
        <el-tab-pane label="已完成" name="4"/>
<!--        <el-tab-pane v-for="(dict,index) in logistics_status" :key="index" :label="dict.label" :name="dict.value"/>-->
      </el-tabs>

      <el-table border v-loading="loading" :data="cardOrderLogisticsList">
        <el-table-column label="商品信息" header-align="center" align="left">
          <template #default="scope">
            <div>
              <image-preview :src="scope.row.collageImagePath" :width="100" :height="100" />
            </div>
            <div style="margin-top: 5px">
              <el-link type="primary">{{scope.row.cardCollageName}}</el-link>
            </div>
            <div style="margin-top: 5px" v-if="scope.row.cardCollageVo">
              <el-link type="success">拼团编号：{{scope.row.cardCollageVo.collageCode}}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单基础信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="8">
                订单编号：
              </el-col>
              <el-col :span="16">
                {{scope.row.cardOrderNumber}}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="8">
                订单状态：
              </el-col>
              <el-col :span="16">
                <dict-tag :options="logistics_status" :value="scope.row.logisticsStatus"/>
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="8">
                订单数量：
              </el-col>
              <el-col :span="16">
                {{scope.row.count}}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="8">
                订单运费：
              </el-col>
              <el-col :span="16">
                {{scope.row.orderFreight}}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" align="center">
          <template #default="scope">
            <div class="common-flex-image" v-if="scope.row.appUserVo">
              <image-preview :src="scope.row.appUserVo.headPortrait" :width="80" :height="80" />
              <div style="margin-left: 5px; width: 200px">
                <div>
                  用户昵称：{{scope.row.appUserVo.nickName}}
                </div>
                <div style="margin-top: 5px">
                  手机号：{{scope.row.appUserVo.phone}}
                </div>
                <div style="margin-top: 5px">
                  玩家号：{{scope.row.appUserVo.inviteCode}}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="店铺信息" align="center">
          <template #default="scope">
            <div>
              <image-preview :src="scope.row.shopVo.headPortrait" :width="100" :height="100" />
            </div>
            <div style="margin-top: 5px">
              <el-link type="primary">{{scope.row.shopVo.name}}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货信息" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="8">
                收货人姓名：
              </el-col>
              <el-col :span="16">
                {{scope.row.sendName}}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="8">
                收货人电话：
              </el-col>
              <el-col :span="16">
                {{scope.row.sendPhone}}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-col :span="8">
                收货地址：
              </el-col>
              <el-col :span="16">
                {{scope.row.userAddressInfo}}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="物流信息" align="center">
          <template #default="scope">
            <el-row v-if="scope.row.expressageCompany">
              <el-col :span="8">
                物流公司：
              </el-col>
              <el-col :span="16">
                {{ scope.row.expressageCompany }}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px" v-if="scope.row.expressageNumber">
              <el-col :span="8">
                物流单号：
              </el-col>
              <el-col :span="16">
                {{ scope.row.expressageNumber }}
              </el-col>
            </el-row>
            <el-row style="margin-top: 5px" v-if="scope.row.shipTime">
              <el-col :span="8">
                发货时间：
              </el-col>
              <el-col :span="16">
                {{ parseTime(scope.row.shipTime) }}
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="50px">
          <template #default="scope">
            <el-tooltip content="发货" placement="top" v-if="scope.row.logisticsStatus == '2'">
              <el-button link type="primary" icon="Position" @click="handleUpdate(scope.row)">发货</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改球星卡订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="50%" append-to-body>
      <el-descriptions title="收货信息" direction="vertical" :column="3" border style="margin-bottom: 10px">
        <el-descriptions-item label="收货人姓名">{{form.sendName}}</el-descriptions-item>
        <el-descriptions-item label="收货人手机号">{{form.sendPhone}}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{form.userAddressInfo}}{</el-descriptions-item>
      </el-descriptions>
      <el-form ref="cardOrderLogisticsFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="物流公司" prop="expressageComCode">
          <el-select v-model="form.expressageComCode" @focus="placeholderExpressageComCode = '请搜索物流公司'"
                     @blur="placeholderExpressageComCode = '请选择物流公司'" @change="expressageComCodeChange" filterable
                     :placeholder="placeholderExpressageComCode" style="width: 100%" clearable>
            <el-option v-for="(item, index) in expressageInfoList" :key="index" :value="item.expressageComCode"
                       :label="item.expressageCompany" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="expressageNumber">
          <el-input v-model="form.expressageNumber" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="发货时间" prop="shipTime">
          <el-date-picker v-model="form.shipTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CardOrderLogistics" lang="ts">
import { listCardOrderLogistics, getCardOrderLogistics, delCardOrderLogistics, addCardOrderLogistics, updateCardOrderLogistics, queryExpressageInfoList } from '@/api/system/cardOrderLogistics';
import { CardOrderLogisticsVO, CardOrderLogisticsQuery, CardOrderLogisticsForm } from '@/api/system/cardOrderLogistics/types';
import { parseTime } from '../../../utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logistics_status, logistics_source } = toRefs<any>(proxy?.useDict('logistics_status', 'logistics_source'));

const cardOrderLogisticsList = ref<CardOrderLogisticsVO[]>([]);
const expressageInfoList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const cardOrderLogisticsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const placeholderExpressageComCode = ref('请选择物流公司')

  const initFormData: CardOrderLogisticsForm = {
  id: undefined,
  userId: undefined,
  cardOrderId: undefined,
  logisticsStatus: undefined,
  cardOrderNumber: undefined,
  unitPrice: undefined,
  count: undefined,
  orderFreight: undefined,
  threePaymentNumber: undefined,
  userAddressInfo: undefined,
  sendName: undefined,
  sendPhone: undefined,
  cancelTime: undefined,
  payTime: undefined,
  shipTime: undefined,
  receivedTime: undefined,
  shopId: undefined,
  cardCollageId: undefined,
  collageCode: undefined,
  collageImagePath: undefined,
  cardCollageName: undefined,
  playWay: undefined,
  payWay: undefined,
  payBeanId: undefined,
  userInviteCode: undefined,
  logisticsSource: undefined,
  receivedWay: undefined,
  deleteFlag: undefined,
  expressageNumber: undefined,
  expressageComCode: undefined,
  expressageCompany: undefined
}
const data = reactive<PageData<CardOrderLogisticsForm, CardOrderLogisticsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    cardOrderId: undefined,
    logisticsStatus: '-1',
    cardOrderNumber: undefined,
    unitPrice: undefined,
    count: undefined,
    orderFreight: undefined,
    threePaymentNumber: undefined,
    userAddressInfo: undefined,
    sendName: undefined,
    sendPhone: undefined,
    cancelTime: undefined,
    payTime: undefined,
    shipTime: undefined,
    receivedTime: undefined,
    shopId: undefined,
    cardCollageId: undefined,
    collageCode: undefined,
    collageImagePath: undefined,
    cardCollageName: undefined,
    playWay: undefined,
    payWay: undefined,
    payBeanId: undefined,
    userInviteCode: undefined,
    logisticsSource: undefined,
    receivedWay: undefined,
    deleteFlag: undefined,
    expressageNumber: undefined,
    expressageComCode: undefined,
    expressageCompany: undefined,
    params: {
    }
  },
  // 表单校验
  rules: {
    expressageNumber: [
      { required: true, message: "请输入快递单号", trigger: "blur" }
    ],//快递单号
    expressageComCode: [
      { required: true, message: "请选择物流公司", trigger: "blur" }
    ],// 物流公司
    shipTime: [
      { required: true, message: "请选择发货时间", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询球星卡订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCardOrderLogistics(queryParams.value);
  cardOrderLogisticsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  cardOrderLogisticsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CardOrderLogisticsVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getCardOrderLogistics(_id);
  Object.assign(form.value, res.data);
  form.value.shipTime = parseTime(new Date());
  queryExpressageInfoListData();
  dialog.visible = true;
  dialog.title = "订单发货";
}

/** 提交按钮 */
const submitForm = () => {
  cardOrderLogisticsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCardOrderLogistics(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addCardOrderLogistics(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/**
 * 查询物流公司列表
 */
const queryExpressageInfoListData = async () => {
  const res = await queryExpressageInfoList();
  expressageInfoList.value = res.data;
}

/**
 * 切换物流公司
 * @param e
 */
const expressageComCodeChange = (e) => {
  let obj = expressageInfoList.value.find(item => {
    return e === item.expressageComCode
  })
  form.value.expressageCompany = obj.expressageCompany
  if(obj.reCheck){
    rules.value.expressageNumber = [
      { required: true, message: "请输入物流单号", trigger: "blur" },
      {pattern: obj.reCheck, message: '请输入正确的物流单号', trigger: 'blur'},
    ]
  }else{
    rules.value.expressageNumber = [
      { required: true, message: "请输入物流单号", trigger: "blur" },
    ]
  }
  if( rules.value.expressageNumber){
    cardOrderLogisticsFormRef.value?.validateField('expressageNumber',(res)=>{})
  }
}

onMounted(() => {
  getList();
});
</script>
